package cn.rwklyd.BookKeeping.service.impl;

import cn.rwklyd.BookKeeping.constant.MessageConstant;
import cn.rwklyd.BookKeeping.mapper.mybatisPlus.PlatformMapper;
import cn.rwklyd.BookKeeping.pojo.Platform;
import cn.rwklyd.BookKeeping.pojo.Result;
import cn.rwklyd.BookKeeping.pojo.User;
import cn.rwklyd.BookKeeping.pojo.vo.LoginUser;
import cn.rwklyd.BookKeeping.service.PlatformService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.util.List;

@Service
@Slf4j
public class PlatformServiceImpl extends ServiceImpl<PlatformMapper, Platform> implements PlatformService {

    /**
     * 获取当前登录用户ID
     */
    private Long getCurrentUserId() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication != null && authentication.getPrincipal() instanceof LoginUser) {
            LoginUser loginUser = (LoginUser) authentication.getPrincipal();
            User user = loginUser.getUser();
            return Long.valueOf(user.getId());
        }
        return null;
    }

    @Override
    @Transactional
    public Result<String> addPlatform(Platform platform) {
        // 获取当前用户ID
        Long userId = getCurrentUserId();
        if (userId == null) {
            return Result.error(MessageConstant.USER_NOT_LOGIN);
        }

        // 设置用户ID
        platform.setUserId(userId);
        
        // 检查平台名称是否已存在
        LambdaQueryWrapper<Platform> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Platform::getUserId, userId)
                   .eq(Platform::getName, platform.getName())
                   .eq(Platform::getIsDeleted, 0);
        
        long count = this.count(queryWrapper);
        if (count > 0) {
            return Result.error("平台名称已存在");
        }
        
        // 设置默认值
        platform.setCreateTime(LocalDateTime.now());
        platform.setUpdateTime(LocalDateTime.now());
        platform.setStatus(1); // 默认启用
        platform.setIsDeleted(0); // 默认未删除
        
        // 保存平台
        boolean success = this.save(platform);
        if (success) {
            return Result.success("添加平台成功");
        } else {
            return Result.error("添加平台失败");
        }
    }

    @Override
    @Transactional
    public Result<String> deletePlatform(Long id) {
        // 获取当前用户ID
        Long userId = getCurrentUserId();
        if (userId == null) {
            return Result.error(MessageConstant.USER_NOT_LOGIN);
        }
        
        // 查询平台是否存在且属于当前用户
        Platform platform = this.getById(id);
        if (platform == null) {
            return Result.error("平台不存在");
        }
        
        if (!platform.getUserId().equals(userId) && platform.getUserId() != 0) {
            return Result.error("无权操作此平台");
        }
        
        // 逻辑删除（将is_deleted设为1）
        platform.setIsDeleted(1);
        platform.setUpdateTime(LocalDateTime.now());
        
        boolean success = this.updateById(platform);
        if (success) {
            return Result.success("删除平台成功");
        } else {
            return Result.error("删除平台失败");
        }
    }

    @Override
    @Transactional
    public Result<String> updatePlatform(Platform platform) {
        // 获取当前用户ID
        Long userId = getCurrentUserId();
        if (userId == null) {
            return Result.error(MessageConstant.USER_NOT_LOGIN);
        }
        
        // 查询平台是否存在
        Platform existingPlatform = this.getById(platform.getId());
        if (existingPlatform == null) {
            return Result.error("平台不存在");
        }
        
        // 检查是否有权限修改
        if (!existingPlatform.getUserId().equals(userId) && existingPlatform.getUserId() != 0) {
            return Result.error("无权操作此平台");
        }
        
        // 检查平台名称是否已存在（排除自身）
        if (StringUtils.hasText(platform.getName()) && !platform.getName().equals(existingPlatform.getName())) {
            LambdaQueryWrapper<Platform> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(Platform::getUserId, userId)
                       .eq(Platform::getName, platform.getName())
                       .eq(Platform::getIsDeleted, 0)
                       .ne(Platform::getId, platform.getId());
            
            long count = this.count(queryWrapper);
            if (count > 0) {
                return Result.error("平台名称已存在");
            }
        }
        
        // 设置更新时间
        platform.setUpdateTime(LocalDateTime.now());
        // 保持用户ID不变
        platform.setUserId(existingPlatform.getUserId());
        
        boolean success = this.updateById(platform);
        if (success) {
            return Result.success("更新平台成功");
        } else {
            return Result.error("更新平台失败");
        }
    }

    @Override
    @Transactional
    public Result<String> updatePlatformStatus(Long id) {
        // 获取当前用户ID
        Long userId = getCurrentUserId();
        if (userId == null) {
            return Result.error(MessageConstant.USER_NOT_LOGIN);
        }
        
        // 查询平台是否存在
        Platform platform = this.getById(id);
        if (platform == null || platform.getIsDeleted() == 1) {
            return Result.error("平台不存在");
        }
        
        // 检查是否有权限修改（只能修改自己的平台）
        if (!platform.getUserId().equals(userId) && platform.getUserId() != 0) {
            return Result.error("无权操作此平台");
        }
        
        // 切换状态（0变1，1变0）
        platform.setStatus(platform.getStatus() == 1 ? 0 : 1);
        platform.setUpdateTime(LocalDateTime.now());
        
        boolean success = this.updateById(platform);
        if (success) {
            return Result.success(platform.getStatus() == 1 ? "启用平台成功" : "禁用平台成功");
        } else {
            return Result.error("更新平台状态失败");
        }
    }

    @Override
    public Result<Platform> getPlatformById(Long id) {
        // 获取当前用户ID
        Long userId = getCurrentUserId();
        if (userId == null) {
            return Result.error(MessageConstant.USER_NOT_LOGIN);
        }
        
        // 查询平台
        Platform platform = this.getById(id);
        if (platform == null || platform.getIsDeleted() == 1) {
            return Result.error("平台不存在");
        }
        
        // 检查是否有权限查看（系统平台或自己的平台）
        if (!platform.getUserId().equals(userId) && platform.getUserId() != 0) {
            return Result.error("无权查看此平台");
        }
        
        return Result.success(platform);
    }

    @Override
    public Result<IPage<Platform>> queryPlatforms(Long id, String name, Long userId, Integer page, Integer pageSize) {
        // 获取当前用户ID
        Long currentUserId = getCurrentUserId();
        if (currentUserId == null) {
            return Result.error(MessageConstant.USER_NOT_LOGIN);
        }
        
        // 构建查询条件
        LambdaQueryWrapper<Platform> queryWrapper = new LambdaQueryWrapper<>();
        
        // 基础条件：未删除的
        queryWrapper.eq(Platform::getIsDeleted, 0);
        
        // 用户ID条件处理
        if (userId != null) {
            // 如果指定了用户ID，则查询该用户的平台（需要权限检查，普通用户只能查自己的）
            if (!currentUserId.equals(userId)) {
                // TODO: 这里应该添加管理员权限检查，普通用户不能查看其他用户的平台
                // 暂时简单处理，非本人的查询请求返回错误
                return Result.error("无权查询其他用户的平台");
            }
            queryWrapper.and(wrapper -> wrapper.eq(Platform::getUserId, userId)
                                        .or()
                                        .eq(Platform::getUserId, 0L)); // 包含系统预设平台
        } else {
            // 未指定用户ID，查询所有用户的平台
            // 不添加用户ID限制，查询所有用户的平台数据
        }
        
        // 根据ID查询
        if (id != null) {
            queryWrapper.eq(Platform::getId, id);
        }
        
        // 根据名称模糊查询
        if (StringUtils.hasText(name)) {
            queryWrapper.like(Platform::getName, name);
        }
        
        // 排序：按创建时间降序
        queryWrapper.orderByDesc(Platform::getCreateTime);
        
        // 设置默认值
        if (page == null) page = 1;
        if (pageSize == null) pageSize = 10;
        
        // 分页查询
        Page<Platform> pageParam = new Page<>(page, pageSize);
        IPage<Platform> platformPage = this.page(pageParam, queryWrapper);
        
        return Result.success(platformPage);
    }

    @Override
    public Result<List<Platform>> getAllPlatforms() {
        Result<IPage<Platform>> result = queryPlatforms(null, null, null, 1, Integer.MAX_VALUE);
        if (result.getCode() != 1) {
            return Result.error(result.getMsg());
        }
        return Result.success(result.getData().getRecords());
    }

    @Override
    public Result<IPage<Platform>> getPlatformList(Integer page, Integer pageSize, String name) {
        return queryPlatforms(null, name, null, page, pageSize);
    }
} 